package org.example.DAO;

import org.example.entity.Blog;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BlogDAO {
    private final Connection connection;

    public BlogDAO(Connection connection) {
        this.connection = connection;
    }

    // 添加博客
    public boolean addBlog(Blog blog) throws SQLException {
        String sql = "INSERT INTO Blog (BLOGID, USERID, TITLE, CONTENT, CREATED_AT, STATUS) VALUES (?, ?, ?, ?, ?, ?)";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, blog.getBlogId());
            stmt.setString(2, blog.getUserId());
            stmt.setString(3, blog.getTitle());
            stmt.setString(4, blog.getContent());
            stmt.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
            stmt.setInt(6, blog.getStatus());

            return stmt.executeUpdate() > 0;
        }
    }

    // 更新博客
    public boolean updateBlog(Blog blog) throws SQLException {
        String sql = "UPDATE Blog SET TITLE = ?, CONTENT = ?, UPDATED_AT = ?, STATUS = ? WHERE BLOGID = ?";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, blog.getTitle());
            stmt.setString(2, blog.getContent());
            stmt.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
            stmt.setInt(4, blog.getStatus());
            stmt.setString(5, blog.getBlogId());

            return stmt.executeUpdate() > 0;
        }
    }

    // 删除博客
    public boolean deleteBlog(String blogId) throws SQLException {
        String sql = "DELETE FROM Blog WHERE BLOGID = ?";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, blogId);
            return stmt.executeUpdate() > 0;
        }
    }

    // 根据ID获取博客
    public Blog getBlogById(String blogId) throws SQLException {
        String sql = "SELECT * FROM Blog WHERE BLOGID = ?";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, blogId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return mapBlogFromResultSet(rs);
                }
            }
        }
        return null;
    }

    // 获取用户的所有博客
    public List<Blog> getBlogsByUser(String userId) throws SQLException {
        List<Blog> blogs = new ArrayList<>();
        String sql = "SELECT * FROM Blog WHERE USERID = ? ORDER BY CREATED_AT DESC";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, userId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    blogs.add(mapBlogFromResultSet(rs));
                }
            }
        }
        return blogs;
    }

    // 增加浏览量
    public boolean incrementViewCount(String blogId) throws SQLException {
        String sql = "UPDATE Blog SET VIEW_COUNT = VIEW_COUNT + 1 WHERE BLOGID = ?";

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, blogId);
            return stmt.executeUpdate() > 0;
        }
    }
    public int getUserBlogCount(String userId) throws SQLException {
        String sql = "SELECT COUNT(*) FROM Blog WHERE USERID = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, userId);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }
        }
        return 0;
    }

    public List<Blog> getBlogsByUser(String userId, int offset, int size) throws SQLException {
        List<Blog> blogs = new ArrayList<>();
        String sql = "SELECT * FROM Blog WHERE USERID = ? ORDER BY CREATED_AT DESC LIMIT ? OFFSET ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, userId);
            stmt.setInt(2, size);
            stmt.setInt(3, offset);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    blogs.add(mapBlogFromResultSet(rs));
                }
            }
        }
        return blogs;
    }
    // 从ResultSet映射到Blog对象
    private Blog mapBlogFromResultSet(ResultSet rs) throws SQLException {
        Blog blog = new Blog();
        blog.setBlogId(rs.getString("BLOGID"));
        blog.setUserId(rs.getString("USERID"));
        blog.setTitle(rs.getString("TITLE"));
        blog.setContent(rs.getString("CONTENT"));
        blog.setCreatedAt(rs.getTimestamp("CREATED_AT"));
        blog.setUpdatedAt(rs.getTimestamp("UPDATED_AT"));
        blog.setViewCount(rs.getInt("VIEW_COUNT"));
        blog.setStatus(rs.getInt("STATUS"));
        return blog;
    }

    // 关闭连接（如果独立使用）
    public void close() throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
    }
}